package com.fs.service;

import com.fs.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class FileServiceImpl implements FileService{


    //定义文件的根目录
    private String rootDir = "E:/workspace/fruitShip-images";
//    private String rootDir = "/usr/local/src/images";
    //定义图片服务器网址
    private String rootURL = "http://image.fs.com";

    @Override
    public ImageVO upload(MultipartFile file) {
        //1.获取图片名称，全部转化为小写
        String fileName = file.getOriginalFilename().toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }

        //2.通过校验宽度和高度判断是否为图片 bufferedImage图片包装对象
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width == 0 || height ==0){
                return null;
            }
            //3.实现分目录的存储
            String dataPath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //
            String fileDir = rootDir + dataPath;
            File dirFile = new File(fileDir);
            if(!new File(fileDir).exists()){
                dirFile.mkdirs();
            }

            //4.动态生成UUID
            String UUID = java.util.UUID.randomUUID().toString();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            fileName = UUID + fileType;

            //5.实现文件上传 准备文件全路径
            String path = fileDir + fileName;
            file.transferTo(new File(path));

            //6.准备ImageVO数据返回
            //封装VO对象对象
            String virtualPath = dataPath + fileName;
            //按照要求封装图片网络地址
            String urlPath = rootURL+virtualPath;
            System.out.println(urlPath);
            ImageVO imageVO = new ImageVO(virtualPath, urlPath, fileName);
            return imageVO;

        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException(e);
        }

    }

    @Override
    public void deleteFile(String virtualPath) {
        //准备文件的全路径  本地路径 + 虚拟地址
        String localPath = rootDir + virtualPath;
        //将路径封装为对象
        File file = new File(localPath);
        if(file.exists()){//如果文件存在 则删除
            file.delete();
        }
    }
}
